package com.wzh.navcode.strategy;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wzh.navcode.domain.entity.HotData;
import com.wzh.navcode.domain.vo.JueJinHotTopic;
import com.wzh.navcode.service.CrawlStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wangzh
 * @Version: 1.0
 * @Description: 掘金热搜策略
 */
@Service("juejinStrategy")
@Slf4j
public class JueJinCrawlStrategy implements CrawlStrategy {
    private final static String JUEJIN_URL = "https://api.it8.com.cn/juejin";
    @Override
    public List<HotData> crawl() {
        List<HotData> hotDataList = new ArrayList<>();
        try {
            String res = HttpUtil.get(JUEJIN_URL);
            Object o = JSONUtil.parseObj(res).get("data");
            List<JueJinHotTopic> list = JSONUtil.parseArray(o).toList(JueJinHotTopic.class);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
            String formattedTime = LocalDateTime.now().format(formatter);
            for (JueJinHotTopic hotTopic : list) {
                hotDataList.add(
                        HotData.builder()
                                .title(hotTopic.getTitle())
                                .url(hotTopic.getUrl())
                                .hotValue(String.format("%.1f万", hotTopic.getHot() / 10000.0))
                                .crawlTime("今天" + formattedTime)
                                .platform("掘金")
                                .build());
            }
        } catch (Exception e) {
            log.error("掘金热搜爬取失败", e);
        }
        return hotDataList.subList(0,8);
    }
}
